import mod_entity

class ItemGhost:
    def __init__(self,ID,prototype,location):
        self.ID = ID
        self.prototype = prototype
        self.location = location # LevelNumber, coords
        
    def add(self,brain):
        oldGhost = brain.ghostMap.get(self.ID)
        if oldGhost:
            oldGhost.remove(brain)
        if self.location and not isinstance(self.location,mod_entity.Entity):
            levelNumber,coords = self.location
            levelMemory = brain.getLevelMemory(levelNumber)
            if coords not in levelMemory.itemMap:
                levelMemory.itemMap[coords] = []
            levelMemory.itemMap[coords].append(self)
            brain.ghostMap[self.ID] = self
    
    def remove(self,brain):
        if self.location and not isinstance(self.location,mod_entity.Entity):
            levelNumber,coords = self.location
            levelMemory = brain.getLevelMemory(levelNumber)
            levelMemory.itemMap[coords].remove(self)
            if not levelMemory.itemMap[coords]:
                del levelMemory.itemMap[coords]
            del brain.ghostMap[self.ID]
            levelMemory.extraUpdatedTiles.add(coords)
            
    def __getattr__(self,name):
        return getattr(self.prototype,name)
    
    
class EntityGhost:
    def __init__(self,ID,prototype,location):
        self.ID = ID
        self.prototype = prototype
        self.location = location # LevelNumber, coords
        
    def add(self,brain):
        oldVersion = brain.ghostMap.get(self.ID)
        if oldVersion:
            oldVersion.remove(brain)
        if self.location:
            levelNumber,coords = self.location
            levelMemory = brain.getLevelMemory(levelNumber)
            oldGhostThere = levelMemory.entityMap.get(coords)
            if oldGhostThere:
                oldGhostThere.remove(brain)
            if coords in levelMemory.entityMap:
                raise GhostSpaceOccupiedError(self.location)
            levelMemory.entityMap[coords] = self
            brain.ghostMap[self.ID] = self
        
    def remove(self,brain):
        if self.location:
            levelNumber,coords = self.location
            levelMemory = brain.getLevelMemory(levelNumber)
            del levelMemory.entityMap[coords]
            del brain.ghostMap[self.ID]
            levelMemory.extraUpdatedTiles.add(coords)
            
    def __getattr__(self,name):
        return getattr(self.prototype,name)


class GhostSpaceOccupiedError(Exception):
    def __init__(self,value):
        self.value = value
    def __str__(self):
        return repr(self.value)
    